//
//  SHFindCarViewController.m
//  UI_CarHome
//
//  Created by dllo on 15/10/21.
//  Copyright (c) 2015年 沈浩. All rights reserved.
//

#import "SHFindCarViewController.h"
#import "SHHandle.h"
#import "SHModel.h"
#import "SHBrandTableViewCell.h"
#import "SHFindCarModel.h"
#import "SHFindCarDetailModel.h"
#import "SHFindCarDetailCell.h"
#import "SHFindDetailViewController.h"
#import "SHRightCarModel.h"
@interface SHFindCarViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *brandlistArr;
@property(nonatomic, retain)MBProgressHUD *hud;
@property(nonatomic, retain)NSMutableArray *listArr;
@property(nonatomic, retain)NSDictionary *dic;
@property(nonatomic, retain)NSMutableArray *hotbrandlistArr;
@property(nonatomic, retain)NSMutableArray *hotseriesArr;
@property(nonatomic, retain)UICollectionView *collectionView;

@property(nonatomic, retain)UIView *carView;
@property(nonatomic, retain)UITableView *carTableView;
@property(nonatomic, retain)NSNumber *brandId;

@property(nonatomic, retain)NSMutableArray *detailModelArr;
@property(nonatomic, retain)NSMutableArray *serieslistArr;

@end

@implementation SHFindCarViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_tableView release];
    [_brandlistArr release];
    [_hud release];
    [_listArr release];
    [_dic release];
    [_hotbrandlistArr release];
    [_hotseriesArr release];
    [_collectionView release];
    [_carView release];
    [_carTableView release];
    [_brandId release];
    [_detailModelArr release];
    [_serieslistArr release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH , HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 60;
    self.tableView.tableHeaderView = self.collectionView;
    [_collectionView release];
    // carView
    self.carView = [[UIView alloc] initWithFrame:CGRectMake(WIDTH, 0, 255, HEIGHT)];
    [self.view addSubview:self.carView];
    [_carView release];
    
    [self.carView addSubview:self.carTableView];
    [_carTableView release];
    
    self.view.backgroundColor = BACKGROUNDCOLOR;
    self.carView.backgroundColor = BACKGROUNDCOLOR;
    self.collectionView.backgroundColor = BACKGROUNDCOLOR;
    self.carTableView.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.separatorStyle = SEPARATORSTYLE;
    self.carTableView.separatorStyle = SEPARATORSTYLE;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isNight:) name:@"isNight" object:nil];
    
    self.title = @"找车";
    
    [self createHud];
    [self createData];
    // 添加手势
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(isSwipedHiden:)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.carView addGestureRecognizer:swipe];
    [swipe release];
    
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction:)];
    
}
#pragma mark --夜间模式
- (void)isNight:(NSNotification *)notification {
    [self.collectionView reloadData];
    [self.tableView reloadData];
    [self.carTableView reloadData];
    self.view.backgroundColor = BACKGROUNDCOLOR;
    self.carView.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.backgroundColor = BACKGROUNDCOLOR;
    self.carTableView.backgroundColor = BACKGROUNDCOLOR;
    self.collectionView.backgroundColor = BACKGROUNDCOLOR;
    
    self.tableView.separatorStyle = SEPARATORSTYLE;
    self.carTableView.separatorStyle = SEPARATORSTYLE;
}

- (void)searchAction:(UIBarButtonItem *)button {
    SHSearchViewController *search = [[SHSearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
    [search release];
}

- (void)isSwipedHiden:(UISwipeGestureRecognizer *)swipe {
    [UIView animateWithDuration:1 animations:^{
        self.carView.frame = CGRectMake(WIDTH, 0, 255, HEIGHT);
    }];
}
#pragma mark carTableView
- (UITableView *)carTableView {
    if (!_carTableView) {
        self.carTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 255, HEIGHT) style:UITableViewStylePlain];
        self.carTableView.dataSource = self;
        self.carTableView.delegate = self;
        self.carTableView.rowHeight = 80;
        self.carTableView.sectionHeaderHeight = 25;
    }
    return _carTableView;
}


- (void)createHud
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"正在加载...";
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(80, 80);
        
//        flowLayout.minimumInteritemSpacing = 10;
//        flowLayout.minimumLineSpacing = 10;
        flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
        
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, 200) collectionViewLayout:flowLayout];
        
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        
        [self.collectionView registerClass:[SHFindCarCollectionCell class] forCellWithReuseIdentifier:@"collectionReuse"];
        
    }
    return _collectionView;
}
#pragma mark carTableView
- (void)createCarDataWithBrandId:(NSNumber *)brandId {
    NSString *url = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/modelLibraryHomePage?bid=%@&type=1", brandId]; // 奥迪1
    [SHNetWorkingTool getNetWorking:url block:^(id result) {
        self.detailModelArr = [NSMutableArray array];
        self.detailModelArr = [SHFindCarDetailModel baseModelByArr:result[@"manufacturers"]];
        [self.carTableView reloadData];
    }];
}

#pragma mark --tableview点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        self.carView.frame = CGRectMake(WIDTH - 255, 0, 255, HEIGHT);
        
        [self createCarDataWithBrandId:self.dic[@"sections"][indexPath.section][@"brands"][indexPath.row][@"id"]];
    } else {
        SHFindDetailViewController *detail = [[SHFindDetailViewController alloc] init];
        [self.navigationController pushViewController:detail animated:YES];
        [detail release];
        SHFindCarDetailModel *findCarDetail = self.detailModelArr[indexPath.section];
        NSDictionary *modDic = findCarDetail.serials[indexPath.row];
        SHRightCarModel *model = [[SHRightCarModel alloc] init];
        [model setValuesForKeysWithDictionary:modDic];
        detail.rightModel = model;
        
    }
}
#pragma mark -- collectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [UIView animateWithDuration:1 animations:^{
        self.carView.frame = CGRectMake(WIDTH - 255, 0, 255, HEIGHT);
        
        NSDictionary *hotDic = self.hotbrandlistArr[indexPath.row];
        [self createCarDataWithBrandId:hotDic[@"id"]];
    }];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SHFindCarCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionReuse" forIndexPath:indexPath];
//    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:self.hotbrandlistArr[indexPath.row][@"logo"]]];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:self.hotbrandlistArr[indexPath.row][@"logo"]] placeholderImage:PLACEPICTURE];
    cell.nameLabel.text = self.hotbrandlistArr[indexPath.row][@"name"];
    cell.nameLabel.textColor = TEXTCOLOR;
    cell.nameLabel.textAlignment = NSTextAlignmentCenter;
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.hotbrandlistArr.count;
}
- (void)createData
{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://mrobot.pcauto.com.cn/v2/price/brands?v=picCompare&123" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dic = responseObject;
        self.brandlistArr = [NSMutableArray array];
        self.brandlistArr = [SHFindCarModel baseModelByArr:self.dic[@"sections"]];

        [self.hud removeFromSuperview];
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
//    http://mrobot.pcauto.com.cn/xsp/s/auto/info/v4.7/serials.xsp?serialId=9550&regionId=248&hasDealers=1&fmt=json serialId=%@
//
//    http://mrobot.pcauto.com.cn/v2/price/nav_pictures?serialGroupId=3524&modelId=null
    [SHNetWorkingTool getNetWorking:@"http://mrobot.pcauto.com.cn/configs/pcauto_hot_brands" block:^(id result) {
        self.hotbrandlistArr = [NSMutableArray array];
        self.hotbrandlistArr = result[@"brands"];
        [self.collectionView reloadData];

    }];
}
//http://mrobot.pcauto.com.cn/v2/price/nav_picturesv47?serialGroupId=9550&modelId=0  id

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        static NSString *reuse = @"reuse";
        SHBrandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[SHBrandTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
        }
        
        // 找到当前分区的行
        self.listArr = self.dic[@"sections"][indexPath.section][@"brands"];
        cell.nameLabel.text = self.listArr[indexPath.row][@"name"];
        cell.nameLabel.textColor = TEXTCOLOR;
//        [cell.brandImageView sd_setImageWithURL:[NSURL URLWithString:self.listArr[indexPath.row][@"logo"]]];
        [cell.brandImageView sd_setImageWithURL:[NSURL URLWithString:self.listArr[indexPath.row][@"logo"]] placeholderImage:PLACEPICTURE];
        return cell;

    } else {
        static NSString *reuse = @"brandReuse";
        SHFindCarDetailCell *cell =[tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[SHFindCarDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
        }
        SHFindCarDetailModel *detailModel = self.detailModelArr[indexPath.section];
//        [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:detailModel.serials[indexPath.row][@"photo"]]];
        [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:detailModel.serials[indexPath.row][@"photo"]] placeholderImage:PLACEPICTURE];
        cell.nameLabel.text = detailModel.serials[indexPath.row][@"name"];
        cell.nameLabel.textColor = TEXTCOLOR;
        cell.priceRangeLabel.text = detailModel.serials[indexPath.row][@"priceRange"];
        cell.kindLabel.text = detailModel.serials[indexPath.row][@"kind"];
        return cell;
    }
   }


#pragma mark 设置每个分区显示多少行数据
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        SHFindCarModel *sectionsModel = self.brandlistArr[section];
        NSInteger myInteger = [sectionsModel.rowNum integerValue];
        return myInteger;
    } else {
        SHFindCarDetailModel *detailModel = self.detailModelArr[section];
        return detailModel.serials.count;
    }
   
}
#pragma mark 指定当前的分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        return self.brandlistArr.count;
    } else {
        return self.detailModelArr.count;
    }
    
}
#pragma mark tableView上的索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        return [self.brandlistArr valueForKeyPath:@"index"];
    } else {
        return nil;
    }
    
}
#pragma mark 每个分区的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        SHFindCarModel *findCarModel = self.brandlistArr[section];
        return findCarModel.index;
    } else {
        SHFindCarDetailModel *detailModel = self.detailModelArr[section];
        return detailModel.name;
    }
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
